package router

import (
	"net/http"
	"strings"

	"github.com/gorilla/mux"
	httpSwagger "github.com/swaggo/http-swagger"
)

type RouteBuilder struct {
	baseRouter    *mux.Router // 保存原始router
	currentRouter *mux.Router // 当前操作的router
	prefix        string
	methods       []string
	middlewares   []mux.MiddlewareFunc
}

func NewRouteBuilder(r *mux.Router) *RouteBuilder {
	return &RouteBuilder{
		baseRouter:    r,
		currentRouter: r,
	}
}

func (builder *RouteBuilder) Prefix(path string) *RouteBuilder {
	newPrefix := path
	if builder.prefix != "" {
		newPrefix = builder.prefix + "/" + strings.TrimPrefix(path, "/") // 拼接前缀
	}
	//fmt.Printf("prefix: %s\n", newPrefix)
	return &RouteBuilder{
		baseRouter:    builder.baseRouter,
		currentRouter: builder.currentRouter,
		prefix:        newPrefix,
		methods:       builder.methods,
		middlewares:   builder.middlewares,
	}
}

func (builder *RouteBuilder) WithMethods(methods ...string) *RouteBuilder {
	return &RouteBuilder{
		baseRouter:    builder.baseRouter,
		currentRouter: builder.currentRouter,
		prefix:        builder.prefix,
		methods:       methods,
		middlewares:   builder.middlewares,
	}
}

func (builder *RouteBuilder) GET(path string, handler http.Handler) *RouteBuilder {
	return builder.WithMethods(http.MethodGet).Handle(path, handler)
}

func (builder *RouteBuilder) POST(path string, handler http.Handler) *RouteBuilder {
	return builder.WithMethods(http.MethodPost).Handle(path, handler)
}

func (builder *RouteBuilder) PUT(path string, handler http.Handler) *RouteBuilder {
	return builder.WithMethods(http.MethodPut).Handle(path, handler)
}

func (builder *RouteBuilder) DELETE(path string, handler http.Handler) *RouteBuilder {
	return builder.WithMethods(http.MethodDelete).Handle(path, handler)
}

func (builder *RouteBuilder) PATCH(path string, handler http.Handler) *RouteBuilder {
	return builder.WithMethods(http.MethodPatch).Handle(path, handler)
}

func (builder *RouteBuilder) WithMiddleware(middleware mux.MiddlewareFunc) *RouteBuilder {
	newMiddlewares := append([]mux.MiddlewareFunc{}, builder.middlewares...)
	newMiddlewares = append(newMiddlewares, middleware)
	return &RouteBuilder{
		baseRouter:    builder.baseRouter,
		currentRouter: builder.currentRouter,
		prefix:        builder.prefix,
		methods:       builder.methods,
		middlewares:   newMiddlewares,
	}
}

func (builder *RouteBuilder) Use(middleware mux.MiddlewareFunc) {
	builder.currentRouter.Use(middleware)
}

func (builder *RouteBuilder) Handle(path string, handler http.Handler) *RouteBuilder {
	fullPath := builder.prefix + path
	//fmt.Printf("注册路由: %s\n", fullPath) // 调试输出
	route := builder.currentRouter.Handle(fullPath, handler)

	if len(builder.methods) > 0 {
		route.Methods(builder.methods...)
	}

	for _, m := range builder.middlewares {
		route.Handler(m(handler))
	}

	return builder
}

func (builder *RouteBuilder) SubRouter() *RouteBuilder {
	subRouter := builder.currentRouter.PathPrefix(builder.prefix).Subrouter()
	return &RouteBuilder{
		baseRouter:    builder.baseRouter,
		currentRouter: subRouter,
		prefix:        "",
		methods:       builder.methods,
		middlewares:   builder.middlewares,
	}
}

// Swagger
// Title    		Swagger
// Description   	设置路由为Swagger
// Auth      		alittlexincan@163.com         	"时间（2024/07/22 11:36）"
func (builder *RouteBuilder) Swagger(prefix, dir string) *RouteBuilder {
	builder.currentRouter.PathPrefix(prefix).Handler(http.StripPrefix(prefix, http.FileServer(http.Dir(dir))))
	builder.currentRouter.PathPrefix("/v2/swagger/").Handler(httpSwagger.Handler(httpSwagger.URL("/docs/v2/swagger.json"))).Methods(http.MethodGet)
	builder.currentRouter.PathPrefix("/v3/swagger/").Handler(httpSwagger.Handler(httpSwagger.URL("/docs/v3/swagger.json"))).Methods(http.MethodGet)
	return builder
}
